#include "s3c24xx.h"
#include "mini2440.h"
#include <stdio.h>

#define MAX_ISR 50

void (*isr_handle[MAX_ISR])(void);


void dummy_handle (void)
{

}


void key_handle (void)
{
    unsigned long val = EINTPEND;
    int press_cnt = 0;
    //press_cnt++;

    printf("====== print key %d\r\n", val);
    
    /* turn off all leds */
    GPBDAT |= 0x0f << 5;
    
    EINTPEND |= (1<<8)|(1<<11)|(1<<13)|(1<<14)|(1<<15)|(1<<19);    //clear eint 11,19
    EINTMASK &= ~((1<<8)|(1<<11)|(1<<13)|(1<<14)|(1<<15)|(1<<19)); //enable eint11,19

    if (val & 1<<KEY0_INT) {
        GPBDAT &= ~(1<<LED0);
    }
    if (val & 1<<KEY1_INT) {
        GPBDAT &= ~(1<<LED1);
    }
    if (val & 1<<KEY2_INT) {
        GPBDAT &= ~(1<<LED2);
    }
    if (val & 1<<KEY3_INT) {
        GPBDAT &= ~(1<<LED3);
    }
    if (val & 1<<KEY4_INT) {
        GPBDAT &= ~(1<<LED0) & ~(1<<LED1);
    }
    if (val & 1<<KEY5_INT) {
        GPBDAT &= ~(1<<LED2) & ~(1<<LED3);
    }

}

void timer_handle (void)
{
    if(INTOFFSET == 10) {
        GPBDAT = ~(GPBDAT & (0xf << 5));
    }
}

void watch_dog_handle (void)
{
    if(INTOFFSET == 9) {
        GPBDAT = ~(GPBDAT & (0xf << 5));
    }

    SUBSRCPND = 1<<13;
}


void irq_handle (void)
{
    unsigned long oft = INTOFFSET;

    isr_handle[oft]();

    /* clear interrupt */
    SRCPND = 1 << oft;
    INTPND = 1 << oft;
}

void irq_init (void)
{
    int i;

    /* setup interrupt handler */
    for (i = 0; i < MAX_ISR; ++i) {
        isr_handle[i] = dummy_handle;
    }
    
    isr_handle[5] = key_handle;
    isr_handle[9] = watch_dog_handle;
    isr_handle[10] = timer_handle;
    
    /* enable key interrupt */
    INTMSK &= ~(1<<5);

    /* enable time0 interrupt */
    //INTMSK &= ~(1<<10);

    /* enable watchdog interrupt */
    //INTMSK &= ~(1<<9);
    //INTSUBMSK = ~(1<<13);

    LED_ON(LED0);
}
